package com.iqiyi.pps.epg.api.server.proxy;

import com.alibaba.fastjson.JSONObject;
import com.iqiyi.kiwi.utils.Configuration;
import com.iqiyi.kiwi.utils.HttpClientConnection;
import com.iqiyi.pps.epg.api.aop.annotation.SkipAuthCheck;
import com.iqiyi.pps.epg.api.aop.annotation.SkipInterfaceLog;
import com.iqiyi.pps.epg.api.model.web.channel.TChannelConfig;
import com.iqiyi.pps.epg.api.model.web.news.TNewsDetailsData;
import com.iqiyi.pps.epg.api.model.web.news.TNewsDetailsDataPage;
import com.iqiyi.pps.epg.api.model.web.news.TStatisticNewsDetailsDataPage;
import com.iqiyi.pps.epg.api.model.web.query.TFilter;
import com.iqiyi.pps.epg.api.model.web.query.TPage;
import com.iqiyi.pps.epg.api.model.web.statistic.TStatisticOcrDataPage;
import com.iqiyi.pps.epg.api.model.web.statistic.TStatisticSty2DataPage;
import com.iqiyi.pps.epg.api.model.web.statistic.TStatisticSty2PercentData;
import com.iqiyi.pps.epg.api.server.web.channel.ChannelWebService;
import com.iqiyi.pps.epg.api.server.web.statistic.StatisticWebService;
import com.iqiyi.pps.epg.api.utils.ApiAlertPlatFormUtil;
import com.iqiyi.pps.epg.api.utils.Constants;
import com.iqiyi.pps.epg.api.utils.DateTimeUtil;
import com.iqiyi.pps.epg.api.utils.ServiceUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by karkarrotxu on 2017/4/17.
 */
@Service
public class OtherProxy extends BaseProxy {
    private static Logger logger = LoggerFactory.getLogger(OtherProxy.class);

    private String queryLogin(String email) {
        String url = Configuration.getString("lego.signin.url");
        HttpClientConnection hcc = new HttpClientConnection(url, HttpClientConnection.GET_METHOD);
        hcc.addReqParam("email", email);
        for (int i = 0; i < 3; i++) {
            hcc.connect();
            if (hcc.getStatus() == 200) {
                return hcc.getBody();
            }
        }
        return null;
    }

    @SkipInterfaceLog
    public String permission(String uri) {
        if (StringUtils.isEmpty(uri)) {
            return getResponseWithJsonp(Constants.CODE_ERROR_PARAM, null, PARAMETER_ERROR);
        }
        try {
            logger.info("before username");
            String username = ServiceUtil.getOpUser();
            if (username == null) {
                return getResponseWithJsonp(Constants.CODE_NOSIGNIN, null, "用户未登录");
            }
            logger.info("has username");
            String userId = null;
            String retLogin = queryLogin(username);
            JSONObject userInfo = null;
            if (retLogin != null) {
                JSONObject jsonObject = JSONObject.parseObject(retLogin);
                userInfo = jsonObject.getJSONObject("data");
                if (userInfo == null) {
                    logger.error("username={},result:{}", username, retLogin);
                    return getResponseWithJsonp(Constants.CODE_NOSIGNIN, null, "用户未登录");
                }
                userId = userInfo.getString("uid");
                userInfo.put("devMode", DEV_MODE_FLAG);
            }
            if (userId == null) {
                return getResponseWithJsonp(Constants.CODE_NOSIGNIN, null, "用户未登录");
            }
            logger.info("has userId");
            String url = Configuration.getString("lego.permission.url");
            HttpClientConnection hcc = new HttpClientConnection(url, HttpClientConnection.GET_METHOD);
            hcc.setUrl(url);
            hcc.addReqParam("uid", userId);
            hcc.addReqParam("app", "lego");
            hcc.addReqParam("uri", uri);
            for (int i = 0; i < 3; i++) {
                hcc.connect();
                if (hcc.getStatus() == 200) {
                    String result = hcc.getBody();
                    if (result != null) {
                        JSONObject jsonObject = JSONObject.parseObject(result);
                        if (jsonObject.getString("code").equals("A00000")) {
                            return getResponseWithJsonp(Constants.CODE_SUC, userInfo, null);
                        } else {
                            return getResponseWithJsonp(Constants.CODE_NOPERMISSION, null, null);
                        }
                    }
                    break;
                }
            }
            return getResponseWithJsonp(Constants.CODE_FAIL, null, "获取失败");
        } catch (Exception e) {
            logger.error("[permission]", e);
            return getResponseWithJsonp(Constants.CODE_ERROR, null, INTERFACE_ERROR);
        }
    }

    public String newsDetailsAdd(String dataString) {
        try {
            TNewsDetailsData entity = JSONObject.parseObject(dataString, TNewsDetailsData.class);
            if (StringUtils.isEmpty(entity.getNewsName()) ||
                    StringUtils.isEmpty(entity.getChannelId()) ||
                    StringUtils.isEmpty(entity.getChannelName()) ||
                    StringUtils.isEmpty(entity.getServerRegion()) ||
                    StringUtils.isEmpty(entity.getServerIp()) ||
                    StringUtils.isEmpty(entity.getProductTime()) ||
                    StringUtils.isEmpty(entity.getCostTime())) {
                return Constants.getJsonResponse(Constants.CODE_ERROR, null, PARAMETER_ERROR);
            }
            getNewsService().saveNewsDetailsData(entity);
            return Constants.getResponse(Constants.CODE_SUC, null, Constants.getCode(Constants.CODE_SUC)).toJsonString();
        } catch (Exception e) {
            logger.error("[newsDetailsAdd]", e);
            return Constants.getJsonResponse(Constants.CODE_ERROR, null, ERROR_EXIST);
        }
    }

    @SkipInterfaceLog
    @SkipAuthCheck
    public String suggestStatisticSty2(String field, String word) {
        try {
            Map<String, String> params = new HashMap();
            if (StringUtils.isNotEmpty(field) && StringUtils.isNotEmpty(word)) {
                params.put("LIKES_" + field, word);
            }
            if (params.keySet().size() > 0) {
                TFilter tFilter = new TFilter();
                tFilter.setFilters(params);
                int pageNo = 1;
                int pageSize = 10;
                TPage page = new TPage(-1, pageNo, pageSize, "sty2." + field, "asc", true);
                StatisticWebService.Iface service = getStatisticService();
                List<String> result = service.suggestFieldData(page, tFilter);
                if (result != null) {
                    return Constants.getJsonResponse(Constants.CODE_SUC, result, "获取成功");
                } else {
                    return ServiceUtil.getResponseFail("数据为空");
                }
            } else {
                return ServiceUtil.getResponseError("参数为空");
            }
        } catch (TException te) {
            logger.error("[suggestStatisticSty2][error]", te);
        } catch (Exception e) {
            logger.error("[suggestStatisticSty2][error]", e);
        }
        return null;
    }

    @SkipInterfaceLog
    @SkipAuthCheck
    public String statisticNewsDetailsList(Integer pageNo, Integer pageSize, String newsName, String channelName,
                                           String serverRegion, String serverIp, String startDate, String endDate) {
        pageNo = (pageNo == null || pageNo < 1) ? 1 : pageNo;
        pageSize = (pageSize == null || pageSize < 1) ? 20 : pageSize;

        Map<String, String> params = new HashMap();
        if (StringUtils.isNotEmpty(startDate)) {
            params.put("GET_productTime", startDate);
        }
        if (StringUtils.isNotEmpty(endDate)) {
            params.put("LET_productTime", endDate);
        }
        if (StringUtils.isNotEmpty(newsName)) {
            params.put("LIKES_newsName", newsName);
        }
        if (StringUtils.isNotEmpty(channelName)) {
            params.put("LIKES_channelName", channelName);
        }
        if (StringUtils.isNotEmpty(serverRegion)) {
            params.put("EQS_serverRegion", serverRegion);
        }
        if (StringUtils.isNotEmpty(serverIp)) {
            params.put("EQS_serverIp", serverIp);
        }
        // 筛选条件为空时，默认选取包括当天和之前共七天的数据
        if (!params.containsKey("GET_productTime") && !params.containsKey("LET_productTime")) {
            Calendar calendar = Calendar.getInstance();
            endDate = DateTimeUtil.parseToLString(calendar.getTime());
            calendar.add(Calendar.DATE, -7);
            startDate = DateTimeUtil.parseToSString(calendar.getTime());
            params.put("GET_productTime", startDate + " 00:00:00");
            params.put("LET_productTime", endDate);
        }

        if ("all".equals(serverRegion)) {
            params.remove("EQS_serverRegion");
        }
        if ("all".equals(serverIp)) {
            params.remove("EQS_serverIp");
        }
        TFilter tFilter = new TFilter();
        tFilter.setFilters(params);
        TPage page = new TPage(-1, pageNo, pageSize, "productTime", "desc", true);
        String jsonStrResp = "";
        try {
            TNewsDetailsDataPage tNewsDetailsDataPage = getNewsService().getNewsDetailsData(page, tFilter);
            TStatisticNewsDetailsDataPage tStatisticNewsDetailsDataPage = getNewsService().getStatisticNewsDetailsData(tNewsDetailsDataPage);
            if (tStatisticNewsDetailsDataPage != null) {
                return Constants.getResponse(Constants.CODE_SUC, tStatisticNewsDetailsDataPage, null).toJsonString();
            } else {
                return ServiceUtil.getResponseError(INTERFACE_ERROR + "数据为空");
            }
        } catch (TException te) {
            logger.error("[statisticNewsDetailsList][error]", te);
        } catch (Exception e) {
            logger.error("[statisticNewsDetailsList][error]", e);
        }
        return jsonStrResp;
    }


    @SkipInterfaceLog
    @SkipAuthCheck
    public String newsDetailsList(Integer pageNo, Integer pageSize, String newsName, String channelName, String serverRegion, String serverIp, String startDate, String endDate) {
        String jsonStrResp = "";
        pageNo = (pageNo == null || pageNo < 1) ? 1 : pageNo;
        pageSize = (pageSize == null || pageSize < 1) ? 20 : pageSize;

        Map<String, String> params = new HashMap();
        if (StringUtils.isNotEmpty(startDate)) {
            params.put("GET_productTime", startDate);
        }
        if (StringUtils.isNotEmpty(endDate)) {
            params.put("LET_productTime", endDate);
        }
        if (StringUtils.isNotEmpty(newsName)) {
            params.put("LIKES_newsName", newsName);
        }
        if (StringUtils.isNotEmpty(channelName)) {
            params.put("LIKES_channelName", channelName);
        }
        if (StringUtils.isNotEmpty(serverRegion)) {
            params.put("EQS_serverRegion", serverRegion);
        }
        if (StringUtils.isNotEmpty(serverIp)) {
            params.put("EQS_serverIp", serverIp);
        }
        try {
            // 筛选条件为空时，默认选取包括当天和之前共七天的数据
            if (!params.containsKey("GET_productTime") && !params.containsKey("LET_productTime")) {
                Calendar calendar = Calendar.getInstance();
                endDate = DateTimeUtil.parseToLString(calendar.getTime());
                calendar.add(Calendar.DATE, -7);
                startDate = DateTimeUtil.parseToSString(calendar.getTime());
                params.put("GET_productTime", startDate + " 00:00:00");
                params.put("LET_productTime", endDate);
            }

            if ("all".equals(serverRegion)) {
                params.remove("EQS_serverRegion");
            }
            if ("all".equals(serverIp)) {
                params.remove("EQS_serverIp");
            }
            TFilter tFilter = new TFilter();
            tFilter.setFilters(params);
            TPage page = new TPage(-1, pageNo, pageSize, "productTime", "desc", true);
            TNewsDetailsDataPage tNewsDetailsDataPage = getNewsService().getNewsDetailsData(page, tFilter);
            if (tNewsDetailsDataPage != null) {
                jsonStrResp = Constants.getResponse(Constants.CODE_SUC, tNewsDetailsDataPage, null).toJsonString();
            } else {
                jsonStrResp = Constants.getJsonResponse(Constants.CODE_ERROR, null, "数据为空");
            }
            return jsonStrResp;
        } catch (TException te) {
            logger.error("[newsDetailsList][error]", te);
        } catch (Exception e) {
            logger.error("[newsDetailsList][error]", e);
        }
        return jsonStrResp;

    }

    @SkipInterfaceLog
    @SkipAuthCheck
    public String statisticSty2PercentList(String startDate, String endDate, String channelName,
                                           String albumName, String categoryName) {

        String jsonStrResp = "";
        try {
            Map<String, String> params = new HashMap();
            if (StringUtils.isNotEmpty(startDate)) {
                params.put("GET_statisticTime", startDate);
            }
            if (StringUtils.isNotEmpty(endDate)) {
                params.put("LET_statisticTime", endDate);
            }
            if (StringUtils.isNotEmpty(channelName)) {
                params.put("EQS_channelName", channelName);
            }
            if (StringUtils.isNotEmpty(albumName)) {
                params.put("LIKES_albumName", albumName);
            }
            if (StringUtils.isNotEmpty(categoryName)) {
                params.put("EQS_categoryName", categoryName);
            }

            // 筛选条件为空时，默认选取包括当天和之前共七天的数据
            if (!params.containsKey("GET_statisticTime") && !params.containsKey("LET_statisticTime")) {
                Calendar calendar = Calendar.getInstance();
                endDate = DateTimeUtil.parseToLString(calendar.getTime());
                calendar.add(Calendar.DATE, -7);
                startDate = DateTimeUtil.parseToSString(calendar.getTime());
                params.put("GET_statisticTime", startDate + " 00:00:00");
                params.put("LET_statisticTime", endDate);
            }
            TFilter tFilter = new TFilter();
            tFilter.setFilters(params);
            List<TStatisticSty2PercentData> tStatisticSty2PercentDataList = getStatisticService().getSty2PercentData(null, tFilter);
            if (tStatisticSty2PercentDataList != null) {
                jsonStrResp = Constants.getResponseList(Constants.CODE_SUC, tStatisticSty2PercentDataList, null).toJsonString();
            } else {
                jsonStrResp = Constants.getJsonResponse(Constants.CODE_ERROR, null, "数据为空");
            }
            return jsonStrResp;
        } catch (TException te) {
            logger.error("[statisticSty2PercentList][error]", te);
        } catch (Exception e) {
            logger.error("[statisticSty2PercentList][error]", e);
        }
        return jsonStrResp;
    }

    @SkipInterfaceLog
    @SkipAuthCheck
    public String statisticSty2List(String startDate, String endDate, Integer pageNo, Integer pageSize,
                                    String channelId, String channelName, String programName, String albumName,
                                    String categoryName, String user) {
        String jsonStrResp = "";
        pageNo = (pageNo == null || pageNo < 1) ? 1 : pageNo;
        pageSize = (pageSize == null || pageSize < 1) ? 20 : pageSize;

        Map<String, String> params = new HashMap();
        if (StringUtils.isNotEmpty(startDate)) {
            params.put("GET_statisticTime", startDate);
        }
        if (StringUtils.isNotEmpty(endDate)) {
            params.put("LET_statisticTime", endDate);
        }
        if (StringUtils.isNotEmpty(channelId)) {
            params.put("EQS_channelId", channelId);
        }
        if (StringUtils.isNotEmpty(channelName)) {
            params.put("LIKES_channelName", channelName);
        }
        if (StringUtils.isNotEmpty(programName)) {
            params.put("LIKES_programName", programName);
        }
        if (StringUtils.isNotEmpty(albumName)) {
            params.put("LIKES_albumName", albumName);
        }
        if (StringUtils.isNotEmpty(categoryName)) {
            params.put("EQS_categoryName", categoryName);
        }
        if (StringUtils.isNotEmpty(user)) {
            params.put("LIKES_user", user);
        }
        try {
            // 筛选条件为空时，默认选取包括当天和之前共七天的数据
            if (!params.containsKey("GET_statisticTime") && !params.containsKey("LET_statisticTime")) {
                Calendar calendar = Calendar.getInstance();
                endDate = DateTimeUtil.parseToLString(calendar.getTime());
                calendar.add(Calendar.DATE, -7);
                startDate = DateTimeUtil.parseToSString(calendar.getTime());
                params.put("GET_statisticTime", startDate + " 00:00:00");
                params.put("LET_statisticTime", endDate);
            }
            TFilter tFilter = new TFilter();
            tFilter.setFilters(params);
            TPage page = new TPage(-1, pageNo, pageSize, "statisticTime", "desc", true);
            TStatisticSty2DataPage tStatisticSty2DataPage = getStatisticService().getSty2Data(page, tFilter);
            if (tStatisticSty2DataPage != null) {
                jsonStrResp = Constants.getResponse(Constants.CODE_SUC, tStatisticSty2DataPage, null).toJsonString();
            } else {
                jsonStrResp = Constants.getJsonResponse(Constants.CODE_ERROR, null, "数据为空");
            }
            return jsonStrResp;
        } catch (TException te) {
            logger.error("[statisticSty2List][error]", te);
        } catch (Exception e) {
            logger.error("[statisticSty2List][error]", e);
        }
        return jsonStrResp;
    }

    @SkipInterfaceLog
    @SkipAuthCheck
    public String statisticOcrList(String startDate, String endDate, Integer pageNo, Integer pageSize,
                                   String channelId, String categoryName, String user) {
        String jsonStrResp = "";
        try {
            pageNo = (pageNo == null || pageNo < 1) ? 1 : pageNo;
            pageSize = (pageSize == null || pageSize < 1) ? 20 : pageSize;

            Map<String, String> params = new HashMap();
            if (StringUtils.isNotEmpty(startDate)) {
                params.put("GET_statisticTime", startDate);
            }
            if (StringUtils.isNotEmpty(endDate)) {
                params.put("LET_statisticTime", endDate);
            }
            if (StringUtils.isNotEmpty(channelId)) {
                params.put("EQS_channelId", channelId);
            }
            if (StringUtils.isNotEmpty(categoryName)) {
                params.put("EQS_categoryName", categoryName);
            }
            if (StringUtils.isNotEmpty(user)) {
                params.put("LIKES_user", user);
            }

            // 筛选条件为空时，默认选取包括当天和之前共七天的数据
            if (!params.containsKey("GET_statisticTime") && !params.containsKey("LET_statisticTime")) {
                Calendar calendar = Calendar.getInstance();
                endDate = DateTimeUtil.parseToLString(calendar.getTime());
                calendar.add(Calendar.DATE, -7);
                startDate = DateTimeUtil.parseToSString(calendar.getTime());
                params.put("GET_statisticTime", startDate + " 00:00:00");
                params.put("LET_statisticTime", endDate);
            }
            TFilter tFilter = new TFilter();
            tFilter.setFilters(params);
            TPage page = new TPage(-1, pageNo, pageSize, "statisticTime", "desc", true);
            TStatisticOcrDataPage tStatisticOcrDataPage = getStatisticService().getOcrData(page, tFilter);
            if (tStatisticOcrDataPage != null) {
                jsonStrResp = Constants.getResponse(Constants.CODE_SUC, tStatisticOcrDataPage, null).toJsonString();
            } else {
                jsonStrResp = Constants.getJsonResponse(Constants.CODE_ERROR, null, "数据为空");
            }
            return jsonStrResp;
        } catch (TException te) {
            logger.error("[getStatisticOcrData][error]", te);
        } catch (Exception e) {
            logger.error("[getStatisticOcrData][error]", e);
        }
        return jsonStrResp;
    }


    public String editConfig(String data) {
        try {
            ChannelWebService.Iface service = ServiceUtil.getChannelService();
            TChannelConfig entity = JSONObject.parseObject(data, TChannelConfig.class);
            int result = service.editConfig(entity);
            if (result > 0) {
                return getResponseWithJsonp(Constants.CODE_SUC, result, "修改成功");
            } else if (result == -2) {
                return getResponseWithJsonp(Constants.CODE_FAIL, result, "该类型的索引已存在，请填写其他索引");
            } else {
                return getResponseWithJsonp(Constants.CODE_FAIL, result, "修改失败");
            }
        } catch (Exception e) {
            logger.error("[editConfig]", e);
            return getResponseWithJsonp(Constants.CODE_ERROR, null, INTERFACE_ERROR);
        }
    }

    public String addConfig(String data) {
        try {
            ChannelWebService.Iface service = ServiceUtil.getChannelService();
            TChannelConfig entity = null;
            try {
                entity = JSONObject.parseObject(data, TChannelConfig.class);
            } catch (Exception e) {
                return getResponseWithJsonp(Constants.CODE_FAIL, null, "填写参数错误");
            }
            // Verify data
            if (null == entity || StringUtils.isBlank(entity.getType()) || StringUtils.isBlank(entity.getVal()) ||
                    StringUtils.isBlank(entity.getDesc())) {
                return getResponseWithJsonp(Constants.CODE_FAIL, null, "填写参数错误");
            }
            int result = service.saveConfig(entity);
            if (result > 0) {
                return getResponseWithJsonp(Constants.CODE_SUC, result, "添加成功");
            } else if (result == -2) {
                return getResponseWithJsonp(Constants.CODE_FAIL, result, "该类型的索引已存在，请填写其他索引");
            } else {
                return getResponseWithJsonp(Constants.CODE_FAIL, result, "添加失败");
            }
        } catch (Exception e) {
            logger.error("[addConfig]", e);
            return getResponseWithJsonp(Constants.CODE_ERROR, null, INTERFACE_ERROR);
        }
    }

    @SkipInterfaceLog
    public String queryConfigs(String type, String status, String descr) {
        try {
            ChannelWebService.Iface service = ServiceUtil.getChannelService();
            if (type == null) {
                type = "";
            }
            if (status == null) {
                status = "";
            }

            if (descr == null) {
                descr = "";
            }

            List<TChannelConfig> result = service.filterConfigs(type, status, descr);
            if (result != null) {
                return getResponseWithJsonp(Constants.CODE_SUC, result, null);
            } else {
                return getResponseWithJsonp(Constants.CODE_FAIL, null, "获取失败");
            }
        } catch (Exception e) {
            logger.error("[queryConfigs]", e);
            return getResponseWithJsonp(Constants.CODE_ERROR, null, INTERFACE_ERROR);
        }
    }

    @SkipInterfaceLog
    @SkipAuthCheck
    public String doSendAlert(String dataString) {
        JSONObject data = JSONObject.parseObject(dataString);
        JSONObject sendData = new JSONObject();
        sendData.put("content", data.getString("content"));
        ApiAlertPlatFormUtil.doSendDefault(sendData.toJSONString(), data.getString("user"), data.getIntValue("notifyType"));
        return Constants.getResponse(Constants.CODE_SUC, null, "操作成功").toJsonString();
    }
}
